import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import {
  List,
  Card,
  Row,
  Col,
  Radio,
  Input,
  Icon,
  TreeSelect,
  Avatar,
  Modal,
  message,
  Form,
  Upload,
  Select,
  Button,
  Steps,
  InputNumber,
  Spin,
} from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis';
import styles from './CrowdList.less';

const { TextArea } = Input;
const Option = Select.Option;
const FormItem = Form.Item;
const { Step } = Steps;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { Search } = Input;

@connect(({ crowd, loading }) => ({
  crowd,
  loading: loading.models.list,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        id: props.values.id,
        name: props.values.name,
        charge: props.values.charge,
        is_free: props.values.is_free,
        detailed: props.values.detailed,
        nick_name: props.values.nick_name,
        introduce: props.values.introduce,
        headimgurl: props.values.headimgurl,
        is_private: props.values.is_private,
        classify_id: props.values.classify_id,
      },
      currentStep: 0,
      is_free: props.values.is_free,
      imageUrl: props.values.headimgurl,
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 3) {
            this.forward();
          } else {
            handleUpdate(formVals);
          }
        }
      );
    });
  };

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  beforeUpload(file) {
    //限制图片 格式、size、分辨率
    const isJPG = file.type === 'image/jpeg';
    const isGIF = file.type === 'image/gif';
    const isPNG = file.type === 'image/png';
    if (!(isJPG || isGIF || isPNG)) {
      Modal.error({
        title: '只能上传JPG 、JPEG 、GIF、 PNG格式的图片~',
      });
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      Modal.error({
        title: '超过2M限制 不允许上传~',
      });
    }
    return (isJPG || isGIF || isPNG) && isLt2M;
  }

  handleChange = info => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
          imageUrl,
          loading: false,
        })
      );
    }
  };

  chargeOnchange = value => {
    this.setState({ is_free: value });
  };

  renderContent = (currentStep, formVals) => {
    const {
      form,
      handleUpdate,
      crowd: { classData },
    } = this.props;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const { is_free, introduce, detailed } = this.state;
    const imageUrl = this.state.imageUrl == undefined ? formVals.headimgurl : this.state.imageUrl;
    const controls = [
      'undo',
      'bold',
      'underline',
      'text-color',
      'separator',
      'font-size',
      'line-height',
      'letter-spacing',
      'separator',
      'clear',
      'media',
    ];
    const myUploadFn = param => {
      const serverURL = 'https://community.guoxiaoge.cn/api/0.0.1/tool/upload/img';
      const xhr = new XMLHttpRequest();
      const fd = new FormData();

      const successFn = response => {
        // 假设服务端直接返回文件上传后的地址
        // 上传成功后调用param.success并传入上传后的文件地址
        const img_url = JSON.parse(response.currentTarget.response).data.img_path;
        param.success({
          url: img_url,
        });
      };

      const progressFn = event => {
        // 上传进度发生变化时调用param.progress
        param.progress((event.loaded / event.total) * 100);
      };

      const errorFn = response => {
        // 上传发生错误时调用param.error
        param.error({
          msg: '上传失败',
        });
      };

      xhr.upload.addEventListener('progress', progressFn, false);
      xhr.addEventListener('load', successFn, false);
      xhr.addEventListener('error', errorFn, false);
      xhr.addEventListener('abort', errorFn, false);

      fd.append('img', param.file);
      xhr.open('POST', serverURL, true);
      xhr.send(fd);
    };
    const myValidateFn = file => {
      if (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png') {
        if (file.size < 1024 * 1000) {
          return true;
        } else {
          message.error('文件大小不能超过1M');
          return false;
        }
      } else {
        message.error('文件类型只能是JPG,JPEG,PNG格式');
        return false;
      }
    };

    if (currentStep === 1) {
      return [
        <FormItem key="classify_id" {...this.formLayout} label="群分类">
          {form.getFieldDecorator('classify_id', {
            initialValue: formVals.classify_id,
          })(<TreeSelect treeData={classData} style={{ width: '100%' }} />)}
        </FormItem>,
        <FormItem key="is_private" {...this.formLayout} label="是否私密">
          {form.getFieldDecorator('is_private', {
            initialValue: formVals.is_private,
          })(
            <Select style={{ width: '100%' }} onChange={this.chargeOnchange}>
              <Option value={0}>私密</Option>
              <Option value={1}>公开</Option>
            </Select>
          )}
        </FormItem>,
        <FormItem key="headimgurl" {...this.formLayout} label="图片">
          {form.getFieldDecorator('headimgurl', {})(
            <Upload
              name="img"
              listType="picture-card"
              className={styles.avataruploader}
              showUploadList={false}
              action="https://community.guoxiaoge.cn/api/0.0.1/tool/upload/img"
              beforeUpload={this.beforeUpload}
              onChange={this.handleChange}
            >
              {imageUrl ? (
                <img style={{ height: 100 }} src={imageUrl} alt="avatar" />
              ) : (
                uploadButton
              )}
            </Upload>
          )}
        </FormItem>,
      ];
    }

    if (currentStep === 2) {
      return [
        <FormItem key="introduce">
          {form.getFieldDecorator('introduce', {
            rules: [
              {
                required: true,
                message: '请填写列表介绍',
              },
              {
                max: 250,
                message: '最多输入250个字',
              },
            ],
            initialValue: formVals.introduce,
          })(<TextArea style={{ width: '100%', height: 250 }} />)}
        </FormItem>,
      ];
    }

    if (currentStep === 3) {
      return [
        <FormItem key="detailed">
          {form.getFieldDecorator('detailed', {
            validateTrigger: 'onBlur',
            rules: [
              {
                required: true,
                validator: (_, value, callback) => {
                  if (value.isEmpty()) {
                    callback('请输入详细介绍');
                  } else {
                    callback();
                  }
                },
              },
            ],
            initialValue: BraftEditor.createEditorState(formVals.detailed),
          })(
            <BraftEditor
              className="my-editor"
              media={{
                uploadFn: myUploadFn,
                validateFn: myValidateFn,
              }}
              controls={controls}
              placeholder="请输入详细介绍"
            />
          )}
        </FormItem>,
      ];
    }

    return [
      <FormItem key="id" {...this.formLayout}>
        {form.getFieldDecorator('id', {
          initialValue: formVals.id,
        })(<Input type="hidden" />)}
      </FormItem>,
      <FormItem key="nick_name" {...this.formLayout} label="群主">
        {form.getFieldDecorator('nick_name', {
          rules: [{ required: true, message: '请输入群名称！' }],
          initialValue: formVals.nick_name,
        })(
          formVals.name ? (
            <Input readOnly="readonly" placeholder="请输入" />
          ) : (
            <Input placeholder="请输入" />
          )
        )}
      </FormItem>,
      <FormItem key="name" {...this.formLayout} label="群名称">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入群名称！' }],
          initialValue: formVals.name,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="is_free" {...this.formLayout} label="是否收费">
        {form.getFieldDecorator('is_free', {
          rules: [{ required: true, message: '请选择！' }],
          initialValue: formVals.is_free,
        })(
          <Select style={{ width: '100%' }} onChange={this.chargeOnchange}>
            <Option value={0}>收费</Option>
            <Option value={1}>免费</Option>
          </Select>
        )}
      </FormItem>,
      is_free === 0 ? (
        <FormItem key="charge" {...this.formLayout} label="收费金额">
          {form.getFieldDecorator('charge', {
            rules: [{ required: true, message: '请输入收费金额！' }],
            initialValue: formVals.charge,
          })(<InputNumber min={1} max={10000} />)}
        </FormItem>
      ) : null,
    ];
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible } = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 3) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible()}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, handleUpdate } = this.props;
    const { currentStep, formVals } = this.state;
    return (
      <Form onSubmit={handleUpdate}>
        <Modal
          width={670}
          bodyStyle={{ padding: '32px 40px 48px' }}
          destroyOnClose
          title="文章修改"
          visible={updateModalVisible}
          footer={this.renderFooter(currentStep)}
          onCancel={() => handleUpdateModalVisible()}
        >
          <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
            <Step title="基础设置" />
            <Step title="隐私设置" />
            <Step title="列表介绍" />
            <Step title="详细介绍" />
          </Steps>
          {this.renderContent(currentStep, formVals)}
        </Modal>
      </Form>
    );
  }
}

@connect(({ crowd, loading }) => ({
  crowd,
  loading: loading.models.crowd,
}))
@Form.create()
class CrowdList extends PureComponent {
  state = {
    value: 'all',
    formVals: {},
    updateModalVisible: false,
  };
  formLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 13 },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    console.log(this.props);
    dispatch({
      type: 'crowd/fetchCrowdList',
      payload: {
        pageSize: 5,
      },
    });
  }

  subItem = e => {
    this.setState({
      value: e.target.value,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'crowd/fetchCrowdList',
      payload: {
        is_free: e.target.value == 'all' ? '' : e.target.value,
      },
    });
  };

  seachItem = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'crowd/fetchCrowdList',
      payload: {
        name: e,
      },
    });
  };

  deleteItem = e => {
    const { dispatch } = this.props;
    dispatch({
      type: 'crowd/CrowdDel',
      payload: {
        id: e,
      },
    });
  };

  handleUpdateModalVisible = (flag, item) => {
    this.setState({
      updateModalVisible: !!flag,
      formVals: item || {},
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;

    fields.detailed = fields.detailed.toHTML();
    fields.headimgurl = fields.headimgurl ? fields.headimgurl.file.response.data.img_path : null;
    dispatch({
      type: 'crowd/fetchUpdateCrowdInfo',
      payload: {
        ...fields,
      },
    });

    this.handleUpdateModalVisible();
  };

  buttonReset = () => {
    this.props.dispatch({
      type: 'crowd/fetchCrowdList',
    });
  };

  render() {
    const {
      crowd: { list, pagination },
      loading,
      dispatch,
    } = this.props;
    const { formVals, updateModalVisible } = this.state;
    const editAndDelete = currentItem => {
      Modal.confirm({
        title: '删除群',
        content: '确定删除该群吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => this.deleteItem(currentItem.id),
      });
    };

    const Info = ({ title, value, bordered }) => (
      <div className={styles.headerInfo}>
        <span>{title}</span>
        <p>{value}</p>
        {bordered && <em />}
      </div>
    );

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup onChange={this.subItem.bind(this)} defaultValue="all" value={this.state.value}>
          <RadioButton value="all">全部</RadioButton>
          <RadioButton value="1">收费</RadioButton>
          <RadioButton value="0">不收费</RadioButton>
        </RadioGroup>
        <Search
          onSearch={this.seachItem}
          className={styles.extraContentSearch}
          placeholder="请输入群名称"
        />
        <Button onClick={this.buttonReset}>重置</Button>
      </div>
    );

    const ListContent = ({ data }) => (
      <div className={styles.listContent}>
        <div className={styles.listContentItem}>
          <span>群主</span>
          <p style={{ width: 100 }}>{data.nick_name}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>{data.is_free === 1 ? '免费' : '收费'}</span>
          <p>{data.charge}</p>
        </div>
        <div className={styles.listContentItem}>
          <span>创建时间</span>
          <p>{moment(data.created_at).format('YYYY-MM-DD')}</p>
        </div>
      </div>
    );

    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    return (
      <PageHeaderWrapper>
        <div className={styles.standardList}>
          <Card
            className={styles.listCard}
            bordered={false}
            title="群列表"
            style={{ marginTop: 24 }}
            bodyStyle={{ padding: '0 32px 40px 32px' }}
            extra={extraContent}
          >
            <Spin spinning={loading}>
              <List
                size="large"
                rowKey="id"
                pagination={{
                  current: pagination === [] ? 1 : pagination.current,
                  pageSize: pagination === [] ? 5 : pagination.pageSize,
                  total: pagination === [] ? 5 : pagination.total,
                  onChange: (page, pageSize) => {
                    dispatch({
                      type: 'crowd/fetchCrowdList',
                      payload: {
                        page: page,
                        pageSize: pageSize,
                      },
                    });
                  },
                }}
                dataSource={list}
                renderItem={item => (
                  <List.Item
                    actions={[
                      <a onClick={() => this.handleUpdateModalVisible(true, item)}>
                        <Icon type="edit" theme="twoTone" />
                        修改
                      </a>,
                      <a
                        onClick={e => {
                          e.preventDefault();
                          editAndDelete(item);
                        }}
                      >
                        <Icon type="delete" theme="twoTone" />
                        删除
                      </a>,
                    ]}
                  >
                    <List.Item.Meta
                      avatar={<Avatar src={item.headimgurl} shape="square" size="large" />}
                      title={<a href={item.href}>{item.name}</a>}
                      description={
                        <Ellipsis tooltip={true} lines={1}>
                          {item.introduce}
                        </Ellipsis>
                      }
                    />
                    <ListContent data={item} />
                  </List.Item>
                )}
              />
            </Spin>
            {formVals && Object.keys(formVals).length ? (
              <UpdateForm
                {...updateMethods}
                updateModalVisible={updateModalVisible}
                values={formVals}
              />
            ) : null}
          </Card>
        </div>
      </PageHeaderWrapper>
    );
  }
}

export default CrowdList;
